<template>
  <a-card class="j-inner-table-wrapper" :bordered="false">
    <!-- 查询区域 begin -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :form="form">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="线路">
              <j-popup
                v-decorator="['routeNames']"
                :trigger-change="true"
                org-fields="id,route_name"
                dest-fields="routeIds,routeNames"
                code="select_route"
                :multi="true"
                @callback="popupCallback"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库">
              <j-popup
                v-decorator="['storeName']"
                :trigger-change="true"
                :list-data.sync="listData"
                org-fields="id,store_name"
                dest-fields="storeId,storeName"
                code="store_info"
                @callback="popupCallback"
              />
            </a-form-item>
          </a-col>
          <!--          -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="开始时间">
              <a-date-picker
                @change="payTimeStartChange"
                placeholder="请选择开始支付时间"
                :disabled-date="disabledStartDate"
                v-model="payTimeStart"
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="结束时间">
              <a-date-picker
                placeholder="请选择结束支付时间"
                :disabled-date="disabledEndDate"
                @change="payTimeEndChange"
                v-model="payTimeEnd"
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              />
            </a-form-item>
          </a-col>
          <!--          -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons table-operator">
              <a-button type="primary" icon="fund" @click="setForm">生成出货单</a-button>
            </span>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="提货人">
              <a-input v-model="queryParam.proposerName" placeholder="请输入提货人" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="邀请人">
              <j-popup
                v-decorator="['realNames']"
                :trigger-change="true"
                org-fields="id,realname"
                dest-fields="inviteCode,realNames"
                code="sysuser_select"
                :multi="true"
                @callback="popupCallback"
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="订单编号">
              <a-input v-model="queryParam.receiverName" placeholder="请输入订单编号" />
            </a-form-item>
          </a-col> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="订单状态">
              <j-dict-select-tag v-model="queryParam.status" placeholder="请选择订单状态" dictCode="biz_order_status" />
            </a-form-item>
          </a-col>
          <!--          <a-col :xl="4" :lg="4" :md="4" :sm="4">-->
          <!--            <a-form-item>-->
          <!--              <a-checkbox :checked="checked" @change="checkboxChange"> 对账单 </a-checkbox>-->
          <!--            </a-form-item>-->

          <!--          </a-col>-->
          <!--          <a-form-item>-->
          <!--            <a-checkbox :checked="checked" @change="checkboxChange"> 对账单 </a-checkbox>-->
          <!--          </a-form-item>-->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item>
              <a-checkbox :checked="checked" @change="checkboxChange"> 对账单 </a-checkbox>

              <a-button
                style="margin-left: 20px"
                :disabled="!checked"
                type="primary"
                icon="download"
                @click="handleExportXls('订单对账单' + new Date().getTime())"
                v-has="'order:derive'"
                >导出对账单</a-button
              >
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons table-operator">
              <a-button type="primary" icon="search" @click="searchQuery">查询</a-button>
              <a-button type="primary" icon="reload" @click="searchInputReset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域 end -->

    <!-- 操作按钮区域 begin -->
    <div class="table-operator" v-if="!isTeamLeader">
      <!-- <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button> -->

      <!-- <a-button type="primary" icon="download" @click="handleExportXls('biz_order')">导出</a-button> -->
      <!-- <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>

      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />
            <span>删除</span>
          </a-menu-item>
        </a-menu>
        <a-button>
          <span>批量操作</span>
          <a-icon type="down" />
        </a-button>
      </a-dropdown> -->
    </div>
    <!-- 操作按钮区域 end -->

    <!-- table区域 begin -->
    <div>
      <!-- <a-alert type="info" showIcon style="margin-bottom: 16px" v-if="!isTeamLeader">
        <template slot="message">
          <span>已选择</span>
          <a style="font-weight: 600; padding: 0 4px">{{ selectedRowKeys.length }}</a>
          <span>项</span>
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </template>
      </a-alert> -->

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :expandedRowKeys="expandedRowKeys"
        @expand="handleExpand"
        @change="handleTableChange"
      >
        <!-- 内嵌table区域 begin -->
        <template slot="expandedRowRender" slot-scope="record">
          <a-tabs tabPosition="top">
            <a-tab-pane tab="订单列表" key="orderGoods" forceRender>
              <order-goods-sub-table :record="record" />
            </a-tab-pane>
          </a-tabs>
        </template>
        <!-- 内嵌table区域 end -->

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="status_dictText" slot-scope="text, record">
          <div v-html="text" v-if="record.status == -1" style="color: red"></div>
          <div v-html="text" v-else-if="record.status == 0" style="color: orange"></div>
          <div v-html="text" v-else-if="record.status == 3" style="color: yellow"></div>
          <div v-html="text" v-else-if="record.status == 6" style="color: green"></div>
          <div v-html="text" v-else-if="record.status == 10" style="color: darksalmon"></div>
          <div v-html="text" v-else-if="record.status == 9" style="color: darkturquoise"></div>
          <div v-html="text" v-else-if="record.status == 12" style="color: #50bfff"></div>
          <div v-html="text" v-else-if="record.status == 15" style="color: purple"></div>
          <div v-html="text" v-else></div>
        </template>
        <template slot="states" slot-scope="text, record">
          <div v-html="text" v-if="record.states == -1" style="color: orangered"></div>
          <div v-html="text" v-else-if="record.states == 0" style="color: dodgerblue"></div>
          <div v-html="text" v-else-if="record.states == 1" style="color: #50bfff"></div>
          <div v-html="text" v-else style="color: mediumvioletred"></div>
        </template>

        <template slot="imgSlot" slot-scope="text">
          <div style="font-size: 12px; font-style: italic">
            <span v-if="!text">无图片</span>
            <img v-else :src="getImgView(text)" alt="" style="max-width: 80px; height: 25px" />
          </div>
        </template>

        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else ghost type="primary" icon="download" size="small" @click="downloadFile(text)">
            <span>下载</span>
          </a-button>
        </template>

        <template slot="action" slot-scope="text, record" v-if="!isTeamLeader">
          <!--          <a @click="handleEdit(record)">编辑</a>-->
          <!--          <a-divider type="vertical"/>-->
          <a @click="handleDetail(record)">详情</a>
          <!--          <a-divider type="vertical" />-->
          <!--          <a-dropdown>-->
          <!--            <a class="ant-dropdown-link">-->
          <!--              <span>更多 <a-icon type="down" /></span>-->
          <!--            </a>-->
          <!--            <a-menu slot="overlay">-->
          <!--              <a-menu-item>-->
          <!--                <a-popconfirm title="确定删除吗?" @confirm="handleDelete(record.id)">-->
          <!--                  <a>删除</a>-->
          <!--                </a-popconfirm>-->
          <!--              </a-menu-item>-->
          <!--            </a-menu>-->
          <!--          </a-dropdown>-->
        </template>
      </a-table>
    </div>
    <!-- table区域 end -->

    <!-- 表单区域 -->
    <order-modal ref="modalForm" @ok="modalFormOk" />
    <OrderSendModal ref="OrderSendModal" @ok="modalFormOk"></OrderSendModal>
    <Order-delivery-model ref="deliveryOrderModel" @ok="modalFormOk" disabled></Order-delivery-model>
  </a-card>
</template>

<script>
// import { pustGenerateShipmentGoodsBill } from '@/api/order'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import OrderModal from './modules/OrderModal'
import OrderSendModal from './modules/OrderSendModal'
import OrderGoodsSubTable from './subTables/OrderGoodsSubTable'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
// import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import pick from 'lodash.pick'
import JInput from '@/components/jeecg/JInput'
import moment from 'moment'
import OrderDeliveryModel from './modules/OrderDeliveryModel.vue'

export default {
  name: 'OrderList',
  mixins: [JeecgListMixin],
  components: {
    OrderModal,
    OrderGoodsSubTable,
    JDictSelectTag,
    OrderSendModal,
    JInput,
    OrderDeliveryModel,
  },
  props: {
    teamLeaderData: {
      type: String,
      default: '',
    },
    isTeamLeader: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    listData: {
      immediate: true,
      handler(val) {
        if (val) {
          let row = {
            storeId: val[0].id,
            storeName: val[0].store_name,
          }
          this.popupCallback(row)
        }
      },
    },
    teamLeaderData: {
      immediate: true,
      handler(val) {
        if (this.isTeamLeader) {
          if (this.columns[this.columns.length - 1].title == '操作') {
            this.columns.pop()
            this.queryParam.refereesCustomerId = val + ''
            this.searchQuery()
          }
        } else {
          if (this.columns[this.columns.length - 1].title !== '操作') {
            this.columns.push({
              title: '操作',
              dataIndex: 'action',
              align: 'center',
              width: 147,
              scopedSlots: { customRender: 'action' },
            })
          }
        }
      },
    },
  },
  data() {
    return {
      checked: false,
      payTimeStart: null, //开始时间
      payTimeEnd: null, //结束时间
      orderDeliveryList: [],
      form: this.$form.createForm(this),
      listData: null,

      description: '订单列表管理',
      // 表头
      columns: [
        {
          title: '序号',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (t, r, index) => parseInt(index) + 1,
        },
        {
          title: '客户编号',
          align: 'center',
          dataIndex: 'customerId',
        },
        {
          title: '所属门店',
          align: 'center',
          dataIndex: 'shopName',
        },
        {
          title: '订单总金额',
          align: 'center',
          dataIndex: 'totalAmount',
          customRender: (t, r, index) => t + '元',
        },
        {
          title: '应付金额',
          align: 'center',
          dataIndex: 'payAmount',
          customRender: (t, r, index) => t + '元',
        },
        {
          title: '支付编号',
          align: 'center',
          dataIndex: 'payNo',
        },
        {
          title: '订单来源',
          align: 'center',
          dataIndex: 'sourceType_dictText',
        },

        {
          title: '订单类型',
          align: 'center',
          dataIndex: 'orderType_dictText',
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: '支付时间',
          align: 'center',
          dataIndex: 'payTime',
        },

        {
          title: '提货人',
          align: 'center',
          dataIndex: 'proposerName',
        },
        {
          title: '提货人电话',
          align: 'center',
          dataIndex: 'proposerPhone',
        },
        {
          title: '邀请人',
          align: 'center',
          dataIndex: 'realname',
        },
        {
          title: '佣金',
          align: 'center',
          dataIndex: 'commission',
        },
        {
          title: '订单状态',
          align: 'center',
          dataIndex: 'status_dictText',
          scopedSlots: { customRender: 'status_dictText' },
        },
        // {
        //   title: '拼团状态',
        //   align: 'center',
        //   dataIndex: 'states_dictText',
        //   scopedSlots: { customRender: 'states' },
        // },
        /*{
              title: '创建人',
              align: 'center',
              dataIndex: 'createBy',
            },
            {
              title: '创建时间',
              align: 'center',
              dataIndex: 'createTime',
            },*/
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 字典选项
      dictOptions: {},
      // 展开的行test
      expandedRowKeys: [],
      url: {
        list: '/order/order/list',
        delete: '/order/order/delete',
        deleteBatch: '/order/order/deleteBatch',
        exportXlsUrl: '/order/order/exportXls',
        importExcelUrl: '/order/order/importExcel',
      },
    }
  },
  computed: {
    importExcelUrl() {
      return window._CONFIG['domianURL'] + this.url.importExcelUrl
    },
  },
  methods: {
    checkboxChange(e) {
      this.checked = e.target.checked
      this.queryParam.havePaid = e.target.checked === true ? 1 : null
    },
    /*起始时间*/
    payTimeStartChange(date, dateString) {
      this.payTimeStart = date
      this.queryParam.payTimeStart = date == null ? undefined : moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    payTimeEndChange(date, dateString) {
      this.payTimeEnd = date
      this.queryParam.payTimeEnd = date == null ? undefined : moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    moment,
    disabledStartDate(current) {
      return current < moment(this.payTimeEnd).subtract(29, 'days') || current >= moment(this.payTimeEnd)
    },
    disabledEndDate(current) {
      return (
        (current && current < moment(this.payTimeStart).endOf('seconds')) ||
        current > moment(this.payTimeStart).add(30, 'day')
      )
    },
    // 重置
    searchInputReset() {
      this.searchReset()
      this.payTimeStart = null
      this.payTimeEnd = null
      this.checked = false
      this.form.setFieldsValue({ routeNames: '', storeName: '', realNames: '' })
    },
    // 生成出货单
    setForm() {
      let self = this
      let { storeId, routeIds, payTimeStart, payTimeEnd } = self.queryParam
      let arr = []
      if (!!!storeId) arr.push('仓库')
      if (!!!routeIds) arr.push('线路')
      if (!!!payTimeStart) arr.push('支付开始时间')
      if (!!!payTimeEnd) arr.push('支付结束时间')
      let routeNames = self.form.getFieldValue('routeNames')
      let storeName = self.form.getFieldValue('storeName')

      if (arr.length) {
        self.$message.warning(`请先选择${arr.join('，')}等才能生成表单`)
        return
      }
      self.orderDeliveryList = {
        storeId,
        storeName,
        routeNames,
        routeIds,
        payTimeStart,
        payTimeEnd,
        orderId: self.selectedRowKeys.join(','),
      }
      self.handleDeliveryOrder(self.orderDeliveryList)
    },
    //出货单form
    handleDeliveryOrder(orderDeliveryList) {
      this.$refs.deliveryOrderModel.edit(orderDeliveryList)
      this.$refs.deliveryOrderModel.title = '详情'
      this.$refs.deliveryOrderModel.disableSubmit = true
    },
    initDictConfig() {},
    // getTeamLeaderOrderList(id) {
    //   debugger
    //   searchQuery
    // },
    handleExpand(expanded, record) {
      this.expandedRowKeys = []
      if (expanded === true) {
        this.expandedRowKeys.push(record.id)
      }
    },

    handleDetail: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = true
    },

    //发货
    handleSend() {
      console.log(this.selectedRowKeys)
      // let record1 = Object.assign(record,{orderIds:this.selectedRowKeys})
      this.$refs.OrderSendModal.edit({ orderIds: this.selectedRowKeys })
      this.$refs.OrderSendModal.title = '发货'
      this.$refs.OrderSendModal.disableSubmit = false
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.selectedRowKeys = []
      this.loadData()
    },

    popupCallback(row) {
      let type
      if (row.routeIds !== undefined) {
        type = 'routeIds'
      }
      if (row.storeId !== undefined) {
        type = 'storeId'
      }
      if (row.inviteCode !== undefined) {
        type = 'inviteCode'
      }
      this.form.setFieldsValue(pick(row, 'routeNames', 'storeName', 'realNames'))
      this.queryParam[type] = row[type]
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
</style>
